<?php

namespace app\common\libs;


use app\common\model\ImeiSearch;
use app\common\model\Model;
use think\facade\Log;

class ImeiLib
{
    public static function iphoneNetwork(string $imei)
    {
        $url = 'https://www.gsxunlocking.com/api/uapi?format=json&key=' . self::getKey() . '&srv=1011&imei=' . $imei;
        $res = file_get_contents($url);
        $res = json_decode($res, true);
        return $res['result'];
    }

    public static function iphoneSearchBaoxiaoByXuliehao(string $imei)
    {
        $url = 'https://www.gsxunlocking.com/api/uapi?format=json&key=' . self::getKey() . '&srv=1018&imei=' . $imei;
        $res = file_get_contents($url);
        $res = json_decode($res, true);
        return $res['result'];
    }

    public static function iphoneImei2Xuliehao(string $imei)
    {
        $url = 'https://www.gsxunlocking.com/api/uapi?format=json&key=' . self::getKey() . '&srv=1043&imei=' . $imei;
        $res = file_get_contents($url);
        $res = json_decode($res, true);
        return $res['result'];
    }

    public static function getKey()
    {
        return 'EUKDO4O2C60UX66DMF5H';
    }

    public static function iphonewarranty($imei)
    {
        $imeiSearch = ImeiSearch::where('imei', $imei)->find();
        if (!$imeiSearch) {
            $data = [
                'imei'       => $imei,
                'spec'       => '',
                'disk'       => '',
                'color'      => '',
                'memory'     => '',
                'network'    => '',
                'material'   => '',
                'size'       => '',
                'version'    => '',
                'cpu'        => '',
                'xianka'     => '',
                'brand'      => '苹果',
                'category'   => 'Phone',
                'warranty'   => '',
                'id_lock'    => '',
                'similarity' => 0,
                'suggestion' => []
            ];
            $url = 'https://www.gsxunlocking.com/api/uapi?format=json&key=' . self::getKey() . '&srv=1010&imei=' . $imei;
            $res = file_get_contents($url);
            $res = json_decode($res, true);
            $arr = explode('<br>', $res['result']);
            foreach ($arr as $item) {
                list($key, $value) = explode(':', $item);
                if ($key && $value) {
                    if ($key === '设备型号' || $key === '设备型号') {
                        $data['spec'] = trim($value);
                    } else {
                        if ($key === '设备容量') {
                            $data['disk'] = trim($value);
                        } elseif ($key === '设备颜色') {
                            $data['color'] = trim($value);
                        } else {
                            if ($key === '保修状态') {
                                $data['warranty'] .= trim($item);
                            } else {
                                if ($key === '保修状态') {
                                    $data['warranty'] = trim($value);
                                } else {
                                    if ($key === '激活时间') {
                                        $data['warranty'] .= trim($item);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            $data['spec'] = '苹果 ' . $data['spec'];
            $imeiSearch = new ImeiSearch();
            $imeiSearch->raw = $res['result'];
            $imeiSearch->status = 1;
            $imeiSearch->admin_id = request()->adminInfo['admin_id'];
            $imeiSearch->save($data);
            return $data['warranty'];
        }
        return $imeiSearch->warranty;
    }


    public static function phone(string $imei)
    {
        $imeiSearch = ImeiSearch::where('imei', $imei)->find();
        if (!$imeiSearch) {
            $data = [
                'imei'       => $imei,
                'spec'       => '',
                'disk'       => '',
                'color'      => '',
                'memory'     => '',
                'network'    => '',
                'material'   => '',
                'size'       => '',
                'version'    => '',
                'cpu'        => '',
                'xianka'     => '',
                'brand'      => '苹果',
                'category'   => 'Phone',
                'warranty'   => '',
                'id_lock'    => '',
                'similarity' => 0,
                'suggestion' => []
            ];
            $url = 'https://www.gsxunlocking.com/api/uapi?format=json&key=' . self::getKey() . '&srv=1010&imei=' . $imei;
            $res = file_get_contents($url);
            $res = json_decode($res, true);
            $arr = explode('<br>', $res['result']);
            foreach ($arr as $item) {
                list($key, $value) = explode(':', $item);
                if ($key && $value) {
                    if ($key === '设备型号' || $key === '设备型号') {
                        $data['spec'] = trim($value);
                    } else {
                        if ($key === '设备容量') {
                            $data['disk'] = trim($value);
                        } elseif ($key === '设备颜色') {
                            $data['color'] = trim($value);
                        } else {
                            if ($key === '保修状态') {
                                $data['warranty'] = trim($value);
                            } else {
                                if ($key === '保修状态') {
                                    $data['warranty'] = trim($value);
                                }
                            }
                        }
                    }
                }
            }
            $data['spec'] = '苹果 ' . $data['spec'];

            $imeiSearch = new ImeiSearch();
            $imeiSearch->raw = $res['result'];
            $imeiSearch->status = 1;
            $imeiSearch->admin_id = request()->adminInfo['admin_id'];
            $imeiSearch->save($data);
            return $res['result'];
        }
        return $imeiSearch->raw;
    }


    public static function phoneidlock(string $imei)
    {
        $url = 'https://www.gsxunlocking.com/api/uapi?format=json&key=' . self::getKey() . '&srv=1013&imei=' . $imei;
        $res = file_get_contents($url);
        $res = json_decode($res, true);
        if ($res['code'] == 0) {
            return strip_tags(substr($res['result'], strpos($res['result'], '激活锁: ') + 11, strlen($res['result'])));
        }
        return '';
    }


    public static function iphone(string $result, $data)
    {
        $arr = explode('<br>', $result);
        foreach ($arr as $item) {
            list($key, $value) = explode(':', $item);
            if ($key && $value) {
                if ($key === '型号') {
                    $model = trim($value);
                    $arr = explode(' ', $model);
                    $count = count($arr);
                    if (str_contains($result, 'iPad')) {
                        $data['category'] ='pad';
                        $data['color'] = $arr[$count - 1];
                        $data['disk'] = $arr[$count - 2];
                        for ($i = 0; $i < $count - 2; $i++) {
                            $data['spec'] .= $arr[$i] . ' ';
                        }

                    }elseif (str_contains($result, 'Watch')) {
                        $data['category'] ='watch';
                        $data['color'] = $arr[$count - 1];
                        $data['disk'] = $arr[$count - 2];
                        $data['size'] = $arr[$count - 3];
                        for ($i = 0; $i < $count - 3; $i++) {
                            $data['spec'] .= $arr[$i] . ' ';
                        }
                    }elseif (str_contains($result, 'iPhone')){
                        $data['color'] = $arr[$count - 1];
                        $data['disk'] = $arr[$count - 2];
                        for ($i = 0; $i < $count - 2; $i++) {
                            $data['spec'] .= $arr[$i] . ' ';
                        }
                    }





                }
            }
        }
        $data['brand'] = '苹果';
        $data['spec'] = '苹果 ' . $data['spec'];
        $data['spec_list'] = Model::where('brand', $data['brand'])->where('type', 'Phone')->group('spec')->column('spec');
        // 查询id锁
        if (str_contains($result, '激活锁: ')) {
            $data['id_lock'] = strip_tags(substr($result, strpos($result, '激活锁: ') + 11, strlen($result)));
        }
        return $data;
    }


    /**
     * 型号: Xiaomi 10 青春版 8GB+128GB 蓝莓薄荷<br>
     * 型号: Redmi 10X Pro 5G 8GB+ 256GB 星露白
     * 型号: Redmi 10X 4G  6GB+128GB 天际蓝
     * 小米CC9 美图定制版 8GB+256G
     * @param string $result
     * @param array $data
     * @notes
     * @return array
     */
    public static function xiaomi(string $result, array $data): array
    {
        $result = str_replace(' ', ' ', $result);
        $arr = explode('<br>', $result);
        foreach ($arr as $item) {
            if (!$item) {
                continue;
            }
            list($key, $value) = explode(': ', $item);
            if ($key && $value) {
                if ($key === '型号') {
                    $model = trim($value);
                    $arr = explode(' ', $model);
                    $arr =  array_values(array_filter($arr, function ($item) {
                        return $item !== '';
                    })) ;
                    $count = count($arr);
                    $data['color'] = $arr[$count - 1];
                    $data['disk'] = $arr[$count - 2];
                    for ($i = 0; $i < $count - 2; $i++) {
                        $data['spec'] .= $arr[$i] . ' ';
                    }
                } elseif ($key === 'ID激活锁') {
                    $data['id_lock'] = trim($value);
                }
            }
        }
        if (strpos($data['spec'], 'Xiaomi') > -1) {
            $data['spec'] = str_replace('Xiaomi', '小米', $data['spec']);
        }
        if (strpos($data['spec'], '4G') > -1) {
            $data['spec'] = str_replace('4G', '(4G版)', $data['spec']);
        }
        if (strpos($data['spec'], '5G') > -1) {
            $data['spec'] = str_replace('5G', '(5G版)', $data['spec']);
        }
        if (strpos($data['spec'], '至尊纪念版') > -1) {
            $data['spec'] = str_replace('至尊纪念版', '(至尊纪念版)', $data['spec']);
        }
        if (strpos($data['spec'], '透明探索版') > -1) {
            $data['spec'] = str_replace('透明探索版', '(透明探索版)', $data['spec']);
        }
        if (strpos($data['spec'], '美图定制版') > -1) {
            $data['spec'] = str_replace('美图定制版', '(美图定制版)', $data['spec']);
        }
        $data['brand'] = '小米';
        $data['spec_list'] = Model::where('brand', $data['brand'])->group('spec')->column('spec');
        return $data;
    }

    /**
     *
     * IMEI: 867736057850274<br>序列号: 29553/21NT01338<br>型号: Redmi Note 9 Pro 5G 8GB+128G 碧海星辰<br>内存: 8GB<br>激活状态: 已激活<br>激活日期: 2021-02-11<br>保修结束: 2022-02-12
     * @param string $result
     * @param array $data
     * @notes
     * @return array
     */
    public static function redmi(string $result, array $data): array
    {
        $arr = explode('<br>', $result);
        foreach ($arr as $item) {
            if (!$item) {
                continue;
            }
            list($key, $value) = explode(': ', $item);
            if ($key && $value) {
                if ($key === '型号') {
                    $model = trim($value);
                    $arr = explode(' ', $model);
                    $count = count($arr);
                    $data['color'] = $arr[$count - 1];
                    $data['disk'] = $arr[$count - 2];
                    for ($i = 0; $i < $count - 2; $i++) {
                        $data['spec'] .= $arr[$i] . ' ';
                    }
                } elseif ($key === '保修结束') {
                    $data['warranty'] = trim($value);
                }
            }
        }

        $data['brand'] = '红米';
        $data['spec_list'] = Model::where('brand', $data['brand'])->group('spec')->column('spec');
        return $data;
    }


    /**
     *
     * 华为畅享 20e 4GB+128GB 幻夜黑 双卡 全网通版
     * 华为畅享20 SE 4GB+128GB 幻夜黑 双卡 全网通版
     * 华为畅享 50 8GB+128GB 冰晶蓝 双卡 全网通版
     * 华为畅享 50 Pro 8GB+256GB 雪域白 双卡 全网通版
     * 设备型号: 华为畅享20 5G 6GB+128GB 樱雪晴空 双卡 全网通版<br>产品描述: 华为畅享20 5G 6GB+128GB 双卡 全网通版 (WKG-AN00)<br>
     *设备型号: 华为畅享9 Plus 4GB+128GB 樱语粉 双卡 全网通版<br>产品描述: 畅享9 Plus 全网通版 4GB+128GB (JKM-AL00)<br>
     *IMEI: 868749070032167<br>序列号: 2HSYD24113203557<br>设备型号: 华为畅享 70 8GB+128GB 翡冷翠 双卡 全网通版<br>产品描述: 畅享70 全网通版 8GB+128GB (FGD-AL00)<br>
     * @param string $result
     * @param $data
     * @notes
     * @return mixed
     */
    public static function huawei(string $result, $data)
    {
        $arr = explode('<br>', $result);
        foreach ($arr as $item) {
            if (!$item) {
                continue;
            }
            list($key, $value) = explode(': ', $item);
            if ($key && $value) {
                if ($key === '设备型号') {
                    $model = trim($value);
                    $model = str_replace(array(' 双卡', ' 全网通版',' 标准版'), '', $model);
                    if (str_contains($model, ' ')) {
                        $arr = explode(' ', $model);
                        $count = count($arr);
                        if ($count > 0) {
                            $data['color'] = $arr[$count - 1];
                            $data['disk'] = $arr[$count - 2];
                            for ($i = 0; $i < $count - 2; $i++) {
                                $data['spec'] .= $arr[$i] . ' ';
                            }
                        }
                    }
                } elseif ($key === '产品描述') {
                    if (!$data['spec']) {
                        $model = trim($value);
                        $arr = explode(' ', $model);
                        $count = count($arr);
                        if ($count > 0) {
                            $data['spec'] = $arr[0];
                        }
                        $data['disk'] = $arr[$count - 2];
                    }
                }
            }
        }

        if (strpos($data['spec'], '华为 ') === false) {
            $data['spec'] = str_replace('华为', '华为 ', $data['spec']);
        }

        if (strpos($data['spec'], '畅享 20e') > -1) {
            $data['spec'] = str_replace('畅享 20e', '畅享20e', $data['spec']);
        }
        if (strpos($data['spec'], 'HUAWEI') > -1) {
            $data['spec'] = str_replace('HUAWEI', '华为', $data['spec']);
        }
        if (strpos($data['spec'], 'Pro ') > -1) {
            $data['spec'] = str_replace('Pro ', 'Pro', $data['spec']);
        }
        if (strpos($data['spec'], '5G ') > -1) {
            $data['spec'] = str_replace('5G', '(5G版)', $data['spec']);
        }


        $data['brand'] = '华为';
        if (!str_contains($data['spec'], '华为')) {
            $data['spec'] = '华为 ' . $data['spec'];
        }


        $data['spec_list'] = Model::where('brand', $data['brand'])->where('type', 'Phone')->group('spec')->column('spec');
        return $data;
    }

    /**
     *
     * OPPO A92s PDKM00
     * OPPO A72 5G PDYM20
     * @param string $result
     * @param array $data
     * @notes
     * @return array
     */
    public static function oppo(string $result, array $data)
    {
        $arr = explode('<br>', $result);
        foreach ($arr as $item) {
            if (!$item) {
                continue;
            }
            list($key, $value) = explode(': ', $item);
            if ($key && $value) {
                if ($key === '型号') {
                    $data['spec'] = $value;
                } elseif ($key === '内存') {
                    $data['disk'] = trim($value);
                } elseif ($key === '颜色') {
                    $data['color'] = trim($value);
                } elseif ($key === '容量') {
                    $data['disk'] = $data['disk'] . '+' . trim($value);
                } elseif ($key === '保修结束') {
                    $data['warranty'] = trim($value);
                } elseif ($key === '型号描述') {
                    $data['spec'] = str_replace($value, '', $data['spec']);
                }
            }
        }
        $data['brand'] = 'OPPO';
        $data['spec_list'] = Model::where('brand', 'OPPO')->where('type', 'Phone')->group('spec')->column('spec');
        return $data;
    }

    public static function yijia(string $result, array $data)
    {
        $arr = explode('<br>', $result);
        foreach ($arr as $item) {
            if (!$item) {
                continue;
            }
            list($key, $value) = explode(': ', $item);
            if ($key && $value) {
                if ($key === '型号') {
                    $data['spec'] = $value;
                } else {
                    if ($key === '内存') {
                        $data['disk'] = trim($value);
                    } elseif ($key === '颜色') {
                        $data['color'] = trim($value);
                    } elseif ($key === '容量') {
                        $data['disk'] = $data['disk'] . '+' . trim($value);
                    } elseif ($key === '保修结束') {
                        $data['warranty'] = trim($value);
                    } elseif ($key === '型号描述') {
                        $data['spec'] = str_replace($value, '', $data['spec']);
                    }
                }
            }
        }
        $data['brand'] = '一加';
        $data['spec_list'] = Model::where('brand', 'OPPO')->group('spec')->column('spec');
        return $data;
    }

    /**
     * 型号: Y93 3G+64G<br>颜色: 星夜黑<br>激活状态: 已激活<br>保修状态: 过保<br>保修到期: 2020年05月07日<br>电子保卡: 已过期<br>
     * @param string $result
     * @param array $data
     * @notes
     * @return array
     */
    public static function vivo(string $result, array $data)
    {
        $arr = explode('<br>', $result);
        foreach ($arr as $item) {
            if (!$item) {
                continue;
            }
            list($key, $value) = explode(': ', $item);
            if ($key && $value) {
                if ($key === '型号') {
                    list($pec, $disk) = explode(' ', $value);
                    $data['spec'] = $pec;
                    $data['disk'] = trim($disk);
                } else {
                    if ($key === '内存') {
                        $data['memory'] = trim($value);
                    } elseif ($key === '颜色') {
                        $data['color'] = trim($value);
                    } elseif ($key === '容量') {
                        $data['disk'] = trim($value);
                    } elseif ($key === '保修到期') {
                        $data['warranty'] = trim($value);
                    }
                }
            }
        }
        $data['brand'] = 'vivo';
        $data['spec'] = 'vivo ' . $data['spec'];
        $data['spec_list'] = Model::where('brand', 'OPPO')->where('type', 'Phone')->group('spec')->column('spec');
        return $data;
    }

    /**
     * IMEI: 861253068570830<br>型号: iQOO Z7x 8G+256G<br>颜色: 无限橙<br>激活状态: 未激活<br>保修状态: 未激活<br>保修到期: 未激活<br>电子保卡:
     * @param string $result
     * @param array $data
     * @notes
     * @return array
     */
    public static function IQOO(string $result, array $data)
    {
        $arr = explode('<br>', $result);
        foreach ($arr as $item) {
            if (!$item) {
                continue;
            }
            list($key, $value) = explode(': ', $item);
            if ($key && $value) {
                if ($key === '型号') {
                    $specArr = explode(' ', $value);

                    $index = 0;
                    foreach ($specArr as $k => $v) {
                        if (str_contains($v, '+')) {
                            $data['disk'] = trim($v);
                            $index = $k;
                        }
                    }
                    for ($i = 0; $i < $index; $i++) {
                        $data['spec'] .= trim($specArr[$i]);
                    }
                } else {
                    if ($key === '内存') {
                        $data['memory'] = trim($value);
                    } elseif ($key === '颜色') {
                        $data['color'] = trim($value);
                    } elseif ($key === '保修到期') {
                        $data['warranty'] = trim($value);
                    }
                }
            }
        }
        $data['brand'] = 'iQOO';
        if (str_contains($data['spec'], '活力版')) {
            $data['spec'] = str_replace('活力版', '(活力版)', $data['spec']);
        }
        if (str_contains($data['spec'], '标准版')) {
            $data['spec'] = str_replace('标准版', '(标准版)', $data['spec']);
        }


//        $data['spec'] =  $data['spec'];
        $data['spec_list'] = Model::where('brand', 'OPPO')->where('type', 'Phone')->group('spec')->column('spec');
        return $data;
    }


    public static function brand2Func(string $brand)
    {
        $brand = strtolower($brand);
        $brandArr = [
            '苹果' => 'iphone',
            '华为' => 'huawei',
            'oppo' => 'oppo',
            '一加' => 'yijia',
            'vivo' => 'vivo',
            'IQOO' => 'IQOO',
            '小米' => 'xiaomi',
            '红米' => 'redmi',
            '三星' => 'samsung',
        ];

        return $brandArr[$brand];
    }

    public static function search(string $imei, string $brand)
    {
        $brand = strtolower($brand);
        $data = [
            'imei'       => $imei,
            'spec'       => '',
            'disk'       => '',
            'color'      => '待定',
            'memory'     => '',
            'network'    => '',
            'material'   => '',
            'size'       => '',
            'version'    => '',
            'cpu'        => '',
            'xianka'     => '',
            'brand'      => '',
            'category'   => 'Phone',
            'warranty'   => '',
            'id_lock'    => '',
            'similarity' => 0,
            'suggestion' => []
        ];
        $imeiSearch = ImeiSearch::where('imei', $imei)->find();
        if ($imeiSearch) {
            $data = self::handle($brand, $imeiSearch->raw, $data);

            return $data;
        }
        $srvArr = [
            'iphone'  => 1013,
            'huawei'  => 1100,
            'oppo'    => 1104,
            'yijia'   => 1104,
            'vivo'    => 1102,
            'IQOO'    => 1102,
            'xiaomi'  => 1106,
            'samsung' => 1125
        ];
        $srv = $srvArr[$brand];
        $url = 'https://www.gsxunlocking.com/api/uapi?format=json&key=EUKDO4O2C60UX66DMF5H&srv=' . $srv . '&imei=' . $imei;

        Log::channel('imei')->info('imei' . $imei);
        $res = file_get_contents($url);
        Log::channel('imei')->info('res ' . $res);
        $resArr = json_decode($res, true);
        if (!$resArr) {
            throwError('接口异常');
        }
        if ($resArr['code'] != 0) {
            throwError($resArr['result']);
        }
        $data['raw'] = $resArr['result'];

        $data = self::handle($brand, $resArr['result'], $data);
        $imeiSearch = new ImeiSearch();
        $imeiSearch->status = 1;
        $imeiSearch->admin_id = request()->adminInfo['admin_id'] ?? 0;

        $data['disk'] = str_replace('GB', 'G', $data['disk']);
        $imeiSearch->save($data);

        unset($data['raw']);
        return $data;
    }


    public static function handle($brand, $result, $data)
    {
        $data = self::$brand($result, $data);

        $data['spec'] = trim($data['spec'], ' ');
        $suggestion = [];
        foreach ($data['spec_list'] as $spec) {
            $similarity = self::similarity($data['spec'], $spec);
            if ($similarity > 0) {
                $suggestion[$spec] = $similarity;
            }
        }
        arsort($suggestion);

        unset($data['spec_list']);
        if ($suggestion) {
            $data['similarity'] = array_values($suggestion)[0];
            $data['suggestion'] = array_keys($suggestion);

            if ($data['similarity'] < 100) {
            } elseif ($data['similarity'] == 100) {
                $data['spec'] = array_keys($suggestion)[0];
            }
        }


        return $data;
    }


    public static function similarity($str1, $str2)
    {
        $len1 = strlen($str1);
        $len2 = strlen($str2);
        $longest = ($len1 > $len2) ? $len1 : $len2;
        if ($longest == 0) {
            return 100;
        }
        $str1Arr = explode(' ', $str1);

        $str2Arr = explode(' ', $str2);


        $num = 0;
        foreach ($str1Arr as $item) {
            if (in_array($item, $str2Arr)) {
                $num++;
            }
        }
        if ($num == count($str1Arr)) {
            // 计算相似度百分比
            similar_text($str1, $str2, $similarity);
            return $similarity;
        }
        return 0;
    }
}